﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using Eshouse.Entity;
using System.Data;
using System.Text.RegularExpressions;
using System.Reflection;


namespace Eshouse.Bll
{
    public class personAccess
    {
        private ISession session
        {
            set;
            get;
        }
        public personAccess()
        {
            NHibernateHelper help = new NHibernateHelper();
            session = help.GetSession();
        }
        public IList<PersonInfo> GetListByPage(int pageIdx, int size) {

            pageIdx = (pageIdx - 1) * size;
            IList<PersonInfo> list;
            list = session.CreateCriteria(typeof(PersonInfo)).SetFirstResult(pageIdx).SetMaxResults(size).List<PersonInfo>();
            return list;        
        }
        public static int GetUserCount()
        {
            string sql = "select count(PS_ID) from PersonInfo ";
            DatabaseHelper db = new DatabaseHelper();
            object o=  db.ExecuteScalar(sql);
            if (o == null)
                return 10;
            return Convert.ToInt32(o);
        }
        public static bool ResetPwd(string id)
        {
            bool success = false;
            string pwd=publicComm.toMD5("000000");
            string sql = "update personinfo set ps_password='" + pwd + "' where ps_id=@id";
            DatabaseHelper db = new DatabaseHelper();
            db.AddParameter("@id", id);
            if(db.ExecuteNonQuery(sql)>0)
            {
                success = true;
            }
            return success;
        }
        public string GetJsonDT(int pageIdx,int size)
        {
            return publicComm.GetJsonString(GetUserInPage(pageIdx, size),GetUserCount());
        }
        public DataTable GetUserInPage(int pageIdx, int size)
        {
            IList<PersonInfo> list=GetListByPage(pageIdx,size);
            DataTable dt = new DataTable();
            DataColumn col ;
            PersonInfo person = new PersonInfo();
            PropertyInfo[] protertys= person.GetType().GetProperties();
            foreach(PropertyInfo p in protertys )
            {
                col = new DataColumn(p.Name);
                dt.Columns.Add(col);
            }            
            if(list==null)
            {
                return dt;
            }
            DicTable dic;
            foreach(PersonInfo per in list)
            {
                dic = per.region;
                DataRow dr = dt.NewRow();
                dr["Id"] = per.Id;
                dr["PSEmail"]=person.PSEmail;
                dr["PSMobilePhone1"] = per.PSMobilePhone1;
                dr["PSMobilePhone2"] = per.PSMobilePhone2;
                dr["PSPassword"] = per.PSPassword;
                dr["PSRegTime"] = per.PSRegTime.ToString("yyyy-MM-dd hh:mm");
                dr["PSSex"] = per.PSSex == true ? "男" : "女";
                dr["PSLoginTime"] = per.PSLoginTime.ToString("yyyy-MM-dd hh:mm");
                dr["PSState"] = per.PSState == true ? "启用" : "锁定";
                dr["PSTel1"] = per.PSTel1;
                dr["PSTel2"] = per.PSTel2;
                dr["PSTel3"] = per.PSTel3;
                dr["region"] = dic == null ? "" : dic.ItemName;
                dr["Role"] = per.Role.RoleName;
                dr["PSTruename"] = per.PSTruename;
                dr["PSUserName"] = per.PSUserName;
                dt.Rows.Add(dr);
            }
            return dt;


        }
        public bool UpdateUser(PersonInfo p)
        {
            bool secess = true;
            try
            {
                session.Update(p);
                session.Flush();
            }
            catch (Exception ex)
            {
                secess = false;
                logRecord.RecordErr("用户信息更新", ex);
            }
            return secess;
        }
        public bool VerifyUserMsg(PersonInfo p, ref StringBuilder res,int flag)
        {
            bool success = true;
            if (p.PSUserName == "")
            {
                success = false;
                res.Append("用户名不能空!");
            }

            else {
                if (VerifyUserName(p.PSUserName))
                {
                    success = false;
                    res.Append("用户名已经存在!");
                }
            }
            if(p.Role.Id ==0)
              {
                    success = false;
                    res.Append("用户所属角色不能为空!");
                
                }
            if(p.PSPassword !=null)
            {
                if(p.PSPassword.Length<6)
                 {
                  success = false;
                     res.Append("请输入6位以上的密码!");
                 }
            }else{
                success = false;
                     res.Append("请输入6位以上的密码!");
            }
            if(flag==1)
            {
                Regex regpone=new Regex(@"^(13[0-9]|14[0-9]|15[0|3|6|7|8|9]|18[8|9])\d{8}$");
                Regex regtel = new Regex(@"/d{3}-/d{8}|/d{4}-/d{7}|/d{8}|/d{7}");
                
                if(p.PSEmail!=null)
                {
                    Regex reg = new Regex("/w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*");
                    if(!reg.IsMatch(p.PSEmail))
                    {
                        success = false;
                        res.Append("请您输入正确的电子邮件");
                    }
                }
                if(p.PSMobilePhone1!=null)
                {
                    if (!regpone.IsMatch(p.PSMobilePhone1))
                    {
                        success = false;
                        res.Append("请您输入正确的手机号码！");

                    }
                }

                if (p.PSMobilePhone2 != null)
                {
                    if (!regpone.IsMatch(p.PSMobilePhone2))
                    {
                        success = false;
                        res.Append("请您输入正确的手机号码！");

                    }
                }
                if(p.PSTel1!=null)
                {
                    if(!regtel.IsMatch(p.PSTel1))
                    {
                        success = false;
                        res.Append("请输入正确的电话号码!");
                    }
                }
                if (p.PSTel2 != null)
                {
                    if (!regtel.IsMatch(p.PSTel2))
                    {
                        success = false;
                        res.Append("请输入正确的电话号码!");
                    }
                }
                if (p.PSTel3 != null)
                {
                    if (!regtel.IsMatch(p.PSTel3))
                    {
                        success = false;
                        res.Append("请输入正确的电话号码!");
                    }
                }
            }
            return success;
           
        }
        public static bool VerifyUserName(string username)
        {
            bool isexist = false;
            DatabaseHelper help = new DatabaseHelper();
            string sql = "select ps_id from PersonInfo where PS_UserName=@username";
            help.AddParameter("@username", username);
            object o = help.ExecuteScalar(sql);
            if(o!=null)
                isexist=true;
            return isexist;
        }
        public bool DeleteUser(PersonInfo p)
        {
            bool secess = true;
            try
            {
                session.Delete(p);
                session.Flush();
            }
            catch (Exception ex)
            {
                secess = false;
                logRecord.RecordErr("删除用户", ex);
            }
            return secess;
        }
        public bool InsertNewUser(PersonInfo p,string ip)
        {
            DateTime now = DateTime.Now;
            p.PSRegTime = now;
            p.PSLoginTime = now;
            p.PSState = true;
            CRC32Primarykey crc=new CRC32Primarykey();      
            p.Id =crc.createIntID(now.ToString()+"user"+ip+now.Millisecond.ToString());            
            bool secess = true;
            try {
                session.Save(p);
                session.Flush();
            }
            catch(Exception ex)
            {
                secess = false;
                logRecord.RecordErr("用户注册", ex);
            }
            return secess;
        }
        public PersonInfo GetUserById(int id)
        {
            IList<PersonInfo> list=session.CreateQuery("from PersonInfo p where p.Id=?").SetInt32(0,id).List<PersonInfo>();
            if (list == null || list.Count==0)
                return null;
            return list[0];
        }
        public static bool VerifyUserPwd(string pwd,int id)
        {
            bool success = true;
            string sql = "select count(ps_id) from PersonInfo where ps_password=@pwd and ps_id=@id";
            DatabaseHelper db = new DatabaseHelper();
            db.AddParameter("@pwd", publicComm.toMD5(pwd));
            db.AddParameter("@id", id);
            object o=db.ExecuteScalar(sql);
            if(o==null)
                return false;
            if (Convert.ToInt32(o) <= 0)
            {
                return false;
            }
            else
            {

                success = false;
            }
            return success;
        }
        public static string GetRoleNameByUserName(string username)
        {
            string roleName = "";
            string selRoleName = "select s.rolename from personinfo p,sysrole s where p.roleid=s.roleid  and  p.ps_username=@name";
            DatabaseHelper db = new DatabaseHelper();
            db.AddParameter("@name", username);
            object o = db.ExecuteScalar(selRoleName);
            if(o!=null)
            {
                roleName = o.ToString();
            }
            return roleName;
       }
        public static bool Login(string username,string pwd)
        {
            bool ispass = false;
            DatabaseHelper db = new DatabaseHelper();
            db.AddParameter("@username", username);
            db.AddParameter("@pwd", publicComm.toMD5(pwd));
            object o= db.ExecuteScalar("select PS_ID from PersonInfo where PS_UserName=@username and PS_Password=@pwd");
            if (o != null)
                ispass = true;
            return ispass;
        }
        
    }
}
